
import sys 
sys.path.append("..") 
sys.path.append("./") 

import faiss
import torch
import logging
import numpy as np
from tqdm import tqdm
from torch.utils.data import DataLoader
from torch.utils.data.dataset import Subset
from model.common.common import timestr
from model.search.LocFeature2ImgIndex import LocFeature2ImgIndex
from model.search.LocalFeatureSet import LocalFeatureSet
from model.postprocess.process import process_featureset, process_image
from model.search.LocalFeatureIndex import LocalFeatureIndex
import yaml

# import torch.profiler


"""
With this script you can evaluate checkpoints or test models from two popular
landmark retrieval github repos.
The first is https://github.com/naver/deep-image-retrieval from Naver labs,
provides ResNet-50 and ResNet-101 trained with AP on Google Landmarks 18 clean.
$ python eval.py --off_the_shelf=naver --l2=none --backbone=resnet101conv5 --aggregation=gem --fc_output_dim=2048

The second is https://github.com/filipradenovic/cnnimageretrieval-pytorch from
Radenovic, provides ResNet-50 and ResNet-101 trained with a triplet loss
on Google Landmarks 18 and sfm120k.
$ python eval.py --off_the_shelf=radenovic_gldv1 --l2=after_pool --backbone=resnet101conv5 --aggregation=gem --fc_output_dim=2048
$ python eval.py --off_the_shelf=radenovic_sfm --l2=after_pool --backbone=resnet101conv5 --aggregation=gem --fc_output_dim=2048

Note that although the architectures are almost the same, Naver's
implementation does not use a l2 normalization before/after the GeM aggregation,
while Radenovic's uses it after (and we use it before, which shows better
results in VG)
"""

import os
import sys
import torch
import parser_process
import logging
import sklearn
from os.path import join
from datetime import datetime
from torch.utils.model_zoo import load_url
from google_drive_downloader import GoogleDriveDownloader as gdd


# import test_3d
import util
import commons
import datasets.datasets_ws as datasets_ws
from model import network

from model.extractors.FeatureVectorExtractor import FeatureVectorExtractor

from model.common.Context import Context

from tqdm import tqdm

######################################### SETUP #########################################
args = parser_process.parse_arguments()


# args.resume = "checkpoints/retrievalSfM120k-vgg16-gem-b4dcdc6.pth"
# args.dataset_name = "pitts30k"

with open(args.config, "r") as f:
    config = yaml.safe_load(f)
print("check config!! ", config)

start_time = datetime.now()
args.save_dir = join("log", args.save_dir, start_time.strftime('%Y-%m-%d_%H-%M-%S'))
commons.setup_logging(args.save_dir)
commons.make_deterministic(args.seed)
logging.info(f"Arguments: {args}")
logging.info(f"The outputs are being saved in {args.save_dir}")


context = Context()

context.config = config
context.args = args
# config.args = args

######################################### MODEL #########################################
model = FeatureVectorExtractor(args)
model = model.to(args.device)


# Enable DataParallel after loading checkpoint, otherwise doing it before
# would append "module." in front of the keys of the state dict triggering errors
model = torch.nn.DataParallel(model)

if args.pca_dim is None:
    pca = None
else:
    full_features_dim = args.features_dim
    args.features_dim = args.pca_dim
    pca = util.compute_pca(args, model, args.pca_dataset_folder, full_features_dim)

from datasets.dataset_sp import DatasetSP
######################################### DATASETS #########################################

datasets_folder = config["data"]["datasets_folder"]
dataset_name = config["data"]["dataset_name"]
datasets_type = config["data"]["dataset_type"]

if args.datasets_type == "sp":
    test_ds = DatasetSP(context, datasets_folder, dataset_name, "test")
else:
    test_ds = datasets_ws.BaseDataset(args, datasets_folder, dataset_name, "test")
logging.info(f"Test set: {test_ds}")

######################################### TEST on TEST SET #########################################

context.dataset = test_ds
context.fve_model = model
context.test_method = args.test_method
context.pca = pca

def _getBaseFeatureSet(cfg,ctx):
    feature_set = LocalFeatureSet(cfg,ctx)
    if feature_set.read() < 0:
        eval_ds = ctx.dataset
        pca = ctx.pca
        model = ctx.fve_model.eval()
        test_method = ctx.test_method
        eval_ds.test_method = "hard_resize"
        device = cfg["device"]
        database_subset_ds = Subset(eval_ds, list(range(eval_ds.database_num)))
        database_dataloader = DataLoader(dataset=database_subset_ds, num_workers=cfg["data"]["num_workers"],
                                         batch_size=cfg["data"]["infer_batch_size"], pin_memory=( device == "cuda"))
        with torch.no_grad():
            logging.debug("Extracting database features for evaluation/testing")
            for inputs, indices in tqdm(database_dataloader, ncols=100):
                features = model(inputs.to(device))
                descriptors = features["descriptors"]
                if(torch.is_tensor(descriptors)):
                    descriptors = descriptors.cpu().numpy()
                    features["descriptors"] = descriptors
                    
                imgid = indices.numpy()[0]
                feature_set.add_features(imgid,features)
    
    return feature_set

def _getQueryFeatureSet(cfg,ctx):
    feature_set = LocalFeatureSet(cfg,ctx)
    feature_set.set_feature_dir('query_features')
    if feature_set.read() < 0:
        eval_ds = ctx.dataset
        pca = ctx.pca
        model = ctx.fve_model.eval()
        test_method = ctx.test_method
        eval_ds.test_method = "hard_resize"
        device = cfg["device"]
        queries_subset_ds = Subset(eval_ds, list(range(eval_ds.database_num, eval_ds.database_num+eval_ds.queries_num)))
        database_dataloader = DataLoader(dataset=queries_subset_ds, num_workers=cfg["data"]["num_workers"],
                                         batch_size=cfg["data"]["infer_batch_size"], pin_memory=( device == "cuda"))
        with torch.no_grad():
            logging.debug("Extracting database features for evaluation/testing")
            for inputs, indices in tqdm(database_dataloader, ncols=100):
                features = model(inputs.to(device))
                descriptors = features["descriptors"]
                if(torch.is_tensor(descriptors)):
                    descriptors = descriptors.cpu().numpy()
                    features["descriptors"] = descriptors
                    
                imgid = indices.numpy()[0]
                feature_set.add_features(imgid,features)
    
    return feature_set




baseIndex = LocalFeatureIndex(context)
if baseIndex.read() < 0:
    baseFeatureSet = _getBaseFeatureSet(config,context)
    baseIndex.build_from_featureset(baseFeatureSet)
baseIndex.write()
# logging.info(f"Recalls on {test_ds}: {"recalls_str"}")


# queryFeatureSet = _getQueryFeatureSet(config,context)
# f_set3 = LocalFeatureSet(config,context)
# fstr = "query_features_MaskANMS_" + timestr()
# f_set3.set_feature_dir(fstr)
# cmds = config["fve"]["post_process"]["cmds"]
# process_featureset(cmds,queryFeatureSet,f_set3,context)

logging.info(f"Finished in {str(datetime.now() - start_time)[:-7]}")

pass